package controller

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mygo/app/models"
	"mygo/app/services"
	"mygo/app/tools"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/text/encoding/simplifiedchinese"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type WzCtl struct {
	db      *gorm.DB
	key     []byte
	baseUrl string
}

var Wz = WzCtl{
	key: []byte("91234567890123456789012345678901"),

	//测试环境
	// baseUrl: "E:/温州三澳归档测试/",

	//服务器生产环境
	baseUrl: "\\\\192.168.10.78\\forecastlist\\",
}

func (ctl *WzCtl) Login(c *gin.Context) {
	//var req models.User
	//ctl.db = models.Db
	//
	//c.ShouldBind(&req)
	////cookie, _ := c.Cookie("userId")
	////// 查询数据库
	//var user models.User
	////password, _ := tools.AesEncrypt([]byte(user.Password), ctl.key)
	//
	//ctl.db.Where("username = ? AND password = ?", req.Username, password).First(&user)
	//if user.Username == "" {
	//	tools.ErrorResp(c, 500, "用户名或密码错误")
	//	return
	//}
	//
	////更新登录次数
	//ctl.db.Model(&user).Update("login_count", user.LoginCount+1)
	//
	//var setting models.Settting
	////查找最后一条数据
	//ctl.db.Last(&setting)
	//
	//userIdCookie := &http.Cookie{
	//	Name:     "userId",
	//	Value:    strconv.Itoa(int(user.Id)),
	//	HttpOnly: false,
	//	MaxAge:   setting.MaxAge,
	//	Path:     "/",
	//	Domain:   "",
	//	Secure:   false,
	//}
	//c.SetCookie(userIdCookie.Name, userIdCookie.Value, userIdCookie.MaxAge, "/", "", false, false)
	tools.SuccessResp(c, "登录成功", nil)
}

// GetUser
func (ctl *WzCtl) GetUser(c *gin.Context) {
	ctl.db = models.Db
	//cookie, _ := c.Cookie("userId")
	cookie := c.Query("userId")
	key := "91234567890123456789012345678901"
	decryptCookie := tools.AesDecrypt(cookie, key)
	//转为uint
	decryptCookieInt, _ := strconv.ParseUint(decryptCookie, 10, 64)
	var user models.User
	ctl.db.Preload("Role.Right").First(&user, decryptCookieInt)
	if user.Username == "" {
		tools.ErrorResp(c, 500, "用户不存在")
		return
	}
	tools.SuccessResp(c, "查询成功", user)
}

// GetForeList
func (ctl *WzCtl) GetForeList(c *gin.Context) {
	var err error
	t := c.Query("time")
	ctl.db = models.Db
	var foreList []models.ForeList
	ctl.db.Preload("EmailSends").Preload("FaxSends").Preload("FtpSends").Find(&foreList)
	for i, v := range foreList {
		var sendLog models.SendLog
		//查找是否有发送记录
		err = ctl.db.Where("foreListId = ? AND time = ?", v.Id, t).Last(&sendLog).Error
		//if sendLog.Id != 0 {
		//	foreList[i].IsSend = "1"
		//	foreList[i].SendTime = sendLog.SendTime
		//}
		if err == nil {
			foreList[i].IsSend = "1"
			foreList[i].SendTime = sendLog.SendTime
		}

		var foreDetail models.ForeDetailJson
		ctl.db.Where("foreListId = ? AND time = ?", v.Id, t).First(&foreDetail)
		if foreDetail.Id != 0 {
			//foreList[i].Status = "1"
			if foreDetail.State == "1" {
				foreList[i].Status = "1"
			} else if foreDetail.State == "0" {
				foreList[i].Status = "0"
			} else {
				foreList[i].Status = "2"
			}
			continue
		}
		//else {
		//	//	创建一条
		//	//生成当前时间戳
		//	timeU := tools.GetUnixTime()
		//	//读取json文件
		//	oldName := "./public/yubao/" + v.Code + ".json"
		//	newName := "./public/yubao/" + v.Code + timeU + ".json"
		//	file, _ := os.ReadFile(oldName)
		//	// 写入到新文件
		//	err = os.WriteFile(newName, file, 0666)
		//	if err != nil {
		//		tools.ErrorResp(c, 500, "文件写入失败")
		//	} else {
		//		var foreDetailNew = models.ForeDetail{
		//			ForeListId: v.Id,
		//			Time:       t,
		//			//Id:         tools.GetUuid(),
		//			Data:  v.Code + timeU,
		//			State: "0",
		//		}
		//		ctl.db.Create(&foreDetailNew)
		//	}
		//}
	}
	tools.SuccessResp(c, "查询成功", foreList)
}

// GetForeDetail
func (ctl *WzCtl) GetForeDetail(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	time := c.Query("time")
	idInt, _ := strconv.Atoi(id)

	var foreDetail []models.ForeDetail
	ctl.db.Where("foreListId = ? AND time = ?", id, time).Find(&foreDetail)
	jsonName := ""
	if len(foreDetail) == 0 {
		//生成当前时间戳
		var foreDetailDefault models.ForeDetail
		//查询foreListId=id并且时间=-1
		ctl.db.Where("foreListId = ? AND time = ?", id, "-1").First(&foreDetailDefault)
		timeU := tools.GetUnixTime()
		//读取json文件
		oldName := "./public/yubaotemp/" + foreDetailDefault.Data + ".json"
		newName := "./public/yubao/" + foreDetailDefault.Data + timeU + ".json"
		file1, _ := os.ReadFile(oldName)
		// 写入到新文件
		err = os.WriteFile(newName, file1, 0666)
		if err != nil {
			tools.ErrorResp(c, 500, "未知错误，请重试")
		}
		var foreDetailNew = models.ForeDetail{
			ForeListId: uint(idInt),
			Time:       time,
			Data:       foreDetailDefault.Data + timeU,
			State:      "0",
		}
		ctl.db.Create(&foreDetailNew)
		jsonName = "./public/yubao/" + foreDetailNew.Data + ".json"
	} else {
		jsonName = "./public/yubao/" + foreDetail[0].Data + ".json"
		//	判断是否存在
		if _, err = os.Stat(jsonName); err != nil {
			var foreDetailDefault models.ForeDetail
			//查询foreListId=id并且时间=-1
			ctl.db.Where("foreListId = ? AND time = ?", id, "-1").First(&foreDetailDefault)
			timeU := tools.GetUnixTime()
			//读取json文件
			oldName := "./public/yubaotemp/" + foreDetailDefault.Data + ".json"
			newName := "./public/yubao/" + foreDetailDefault.Data + timeU + ".json"
			file1, _ := os.ReadFile(oldName)
			// 写入到新文件
			err = os.WriteFile(newName, file1, 0666)
			if err != nil {
				tools.ErrorResp(c, 500, "未知错误，请重试")
			}
			var foreDetailNew models.ForeDetail = models.ForeDetail{
				ForeListId: uint(idInt),
				Time:       time,
				//Id:         tools.GetUuid(),
				Data:  foreDetailDefault.Data + timeU,
				State: "0",
			}
			ctl.db.Create(&foreDetailNew)
			jsonName = "./public/yubao/" + foreDetailNew.Data + ".json"
		}
	}
	file, _ := os.ReadFile(jsonName)
	decoder := simplifiedchinese.GBK.NewDecoder()
	file, _ = decoder.Bytes(file)
	var forecast = models.Forecast{}
	json.Unmarshal(file, &forecast)
	if len(foreDetail) != 0 && foreDetail[0].State != "0" {
		tools.SuccessResp(c, "查询成功", forecast)
		return
	}
	//获取foreDetail[0].ForeListId关联的数据
	jsonArr := strings.Split(jsonName, "/")
	jsonArr = strings.Split(jsonArr[len(jsonArr)-1], "1")
	if jsonArr[0] == "hx" {
		handelHx(&forecast, time, ctl.db)
	} else if jsonArr[0] == "df" {
		handelDf(&forecast, time, ctl.db)
	} else if jsonArr[0] == "hy" {
		handelHy(&forecast, time, ctl.db)
	} else if jsonArr[0] == "zb" {
		handelZb(&forecast, time, ctl.db)
	} else if jsonArr[0] == "sa" {
		handelSa(&forecast, time, ctl.db)
	} else if jsonArr[0] == "sz" {
		handelSz(&forecast, time, ctl.db)
	} else if jsonArr[0] == "dt" {
		handelDt(&forecast, time, ctl.db)
	} else if jsonArr[0] == "dtzb" {
		handelDtzb(&forecast, time, ctl.db)
	} else if jsonArr[0] == "ydyl" {
		handelYdyl(&forecast, time, ctl.db)
	} else if jsonArr[0] == "fb" {
		handelFb(&forecast, time, ctl.db)
	}
	tools.SuccessResp(c, "查询成功", forecast)
}

// GetForeDetailLast
func (ctl *WzCtl) GetForeDetailLast(c *gin.Context) {
	ctl.db = models.Db
	id := c.Query("id")
	t := c.Query("time")
	idInt, _ := strconv.Atoi(id)
	var foreDetail []models.ForeDetail
	ctl.db.Where("foreListId = ? AND time < ? AND state != ?", idInt, t, "0").Order("time desc").Find(&foreDetail)
	if len(foreDetail) == 0 {
		tools.SuccessResp(c, "查询成功", nil)
		return
	}
	jsonName := "./public/yubao/" + foreDetail[0].Data + ".json"
	file, _ := os.ReadFile(jsonName)
	decoder := simplifiedchinese.GBK.NewDecoder()
	file, _ = decoder.Bytes(file)
	var forecast = models.Forecast{}
	json.Unmarshal(file, &forecast)
	tools.SuccessResp(c, "查询成功", gin.H{
		"forecast": forecast,
		"time":     foreDetail[0].Time,
	})
}

func handelFb(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for _, report := range forecast.Reports {
		y, m, d := tools.GetNextDay(year, month, day, 1)
		report.Data[0][0].Value = y + "年" + m + "月" + d + "日"
	}
}

func handelYdyl(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for i, report := range forecast.Reports {
		//report.Data[0][0].Value = year + "年" + month + "月" + day + "日"
		if i == 0 {
			for j := 1; j < 4; j++ {
				_, m, d := tools.GetNextDay(year, month, day, j)
				report.Data[0][2*j-1].Value = m + "月" + d + "日"
			}
		} else {
			for j := 0; j < 3; j++ {
				_, m1, d1 := tools.GetNextDay(year, month, day, j)
				_, m, d := tools.GetNextDay(year, month, day, j+1)
				//0-24小时航线要素预报9月22日20时至9月23日20时
				//report.Data[0][j].Value = m + "月" + d + "日"
				str := ""
				if j == 0 {
					str = m1 + "月" + d1 + "日20时至" + m + "月" + d + "日20时"
					report.Data[1][0].Value = str
				} else if j == 1 {
					str = m1 + "月" + d1 + "日20时至" + m + "月" + d + "日20时"
					report.Data[2][0].Value = str
				} else {
					str = m1 + "月" + d1 + "日20时至" + m + "月" + d + "日20时"
					report.Data[3][0].Value = str
				}
			}
		}
	}
}

func handelDtzb(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for i, report := range forecast.Reports {
		if i == 1 {
			for j := 2; j < 9; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "年" + m + "月" + d + "日"
				//这部分操作与上传文件有关，时间那些
				var tide models.Tide
				db.Where("date = ?", timeNew).First(&tide)
				if tide.Id != 0 {
					report.Data[j][1].Value = tide.HighTideOneTime
					report.Data[j][2].Value = tide.HighTideOneData
					report.Data[j][3].Value = tide.HighTideTwoTime
					report.Data[j][4].Value = tide.HighTideTwoData
					report.Data[j][5].Value = tide.LowTideOneTime
					report.Data[j][6].Value = tide.LowTideOneData
					report.Data[j][7].Value = tide.LowTideTwoTime
					report.Data[j][8].Value = tide.LowTideTwoData
				} else {
					for k := 1; k < 9; k++ {
						report.Data[j][k].Value = ""
					}
				}
			}
		} else {
			for j := 1; j < 8; j++ {
				_, m, d := tools.GetNextDay(year, month, day, j)
				report.Data[j][0].Value = m + "月" + d + "日"
			}
		}
	}
}

func handelDt(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for i, report := range forecast.Reports {
		if i == 0 {
			for j := 2; j < 5; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "年" + m + "月" + d + "日"
				//这部分操作与上传文件有关，时间那些
				var tide models.Tide
				db.Where("date = ?", timeNew).First(&tide)
				if tide.Id != 0 {
					report.Data[j][1].Value = tide.HighTideOneTime
					report.Data[j][2].Value = tide.HighTideOneData
					report.Data[j][3].Value = tide.HighTideTwoTime
					report.Data[j][4].Value = tide.HighTideTwoData
					report.Data[j][5].Value = tide.LowTideOneTime
					report.Data[j][6].Value = tide.LowTideOneData
					report.Data[j][7].Value = tide.LowTideTwoTime
					report.Data[j][8].Value = tide.LowTideTwoData
				} else {
					for k := 1; k < 9; k++ {
						report.Data[j][k].Value = ""
					}
				}
			}
		} else {
			for j := 1; j < 4; j++ {
				_, m, d := tools.GetNextDay(year, month, day, j)
				report.Data[0][j].Value = m + "月" + d + "日"
			}
		}
	}
}

func handelSa(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for i, report := range forecast.Reports {
		if i == 1 {
			for j := 2; j < 7; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "-" + m + "-" + d
				//这部分操作与上传文件有关，时间那些
				var tide models.TwcTide
				db.Where("date = ? AND station = ?", timeNew, "玉寮").First(&tide)
				if tide.Id != 0 {
					report.Data[j][1].Value = tide.TimeHigh1
					report.Data[j][2].Value = tide.TideHigh1
					report.Data[j][3].Value = tide.TimeHigh2
					report.Data[j][4].Value = tide.TideHigh2
					report.Data[j][5].Value = tide.TimeLow1
					report.Data[j][6].Value = tide.TideLow1
					report.Data[j][7].Value = tide.TimeLow2
					report.Data[j][8].Value = tide.TideLow2
				} else {
					for k := 1; k < 9; k++ {
						report.Data[j][k].Value = ""
					}
				}
			}
		} else if i == 0 {
			for j := 1; j < 6; j++ {
				_, m, d := tools.GetNextDay(year, month, day, j)
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				//timeNew := y + "-" + m + "-" + d
				report.Data[1][j].Value = strconv.Itoa(j)
				report.Data[2][j].Value = strconv.Itoa(j)
			}
		}
	}
}

func handelSz(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for i, report := range forecast.Reports {
		if i == 0 {
			for j := 2; j < 9; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "年" + m + "月" + d + "日"
				//这部分操作与上传文件有关，时间那些
				var tide models.Tide
				db.Where("date = ?", timeNew).First(&tide)
				if tide.Id != 0 {
					report.Data[j][1].Value = tide.HighTideOneTime
					report.Data[j][2].Value = tide.HighTideOneData
					report.Data[j][3].Value = tide.HighTideTwoTime
					report.Data[j][4].Value = tide.HighTideTwoData
					report.Data[j][5].Value = tide.LowTideOneTime
					report.Data[j][6].Value = tide.LowTideOneData
					report.Data[j][7].Value = tide.LowTideTwoTime
					report.Data[j][8].Value = tide.LowTideTwoData
				} else {
					for k := 1; k < 9; k++ {
						report.Data[j][k].Value = ""
					}
				}
			}
		} else {
			for j := 1; j < 8; j++ {
				_, m, d := tools.GetNextDay(year, month, day, j)
				report.Data[j][0].Value = m + "月" + d + "日"
			}
		}
	}
}

func handelHx(forecast *models.Forecast, time string, db *gorm.DB) {
	offSet := 0.0
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for i, report := range forecast.Reports {
		if i == 2 {
			for j := 2; j < 5; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "-" + m + "-" + d
				//这部分操作与上传文件有关，时间那些
				var tide models.TwcTide
				db.Where("date = ? AND station = ?", timeNew, "浅滩").First(&tide)
				if tide.Id != 0 {
					report.Data[j][1].Value = tide.TimeHigh1
					report.Data[j][2].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideHigh1)/100+offSet, 2)
					report.Data[j][3].Value = tide.TimeHigh2
					report.Data[j][4].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideHigh2)/100+offSet, 2)
					report.Data[j][5].Value = tide.TimeLow1
					report.Data[j][6].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideLow1)/100+offSet, 2)
					report.Data[j][7].Value = tide.TimeLow2
					report.Data[j][8].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideLow2)/100+offSet, 2)
				} else {
					for k := 1; k < 9; k++ {
						report.Data[j][k].Value = ""
					}
				}
			}
		} else {
			for j := 1; j < 4; j++ {
				_, m1, d1 := tools.GetNextDay(year, month, day, j-1)
				_, m, d := tools.GetNextDay(year, month, day, j)
				report.Data[j][0].Value = m1 + "月" + d1 + "日" + "20时" + "-" + m + "月" + d + "日" + "20时"
			}
		}
	}
}

func handelDf(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]

	for i, report := range forecast.Reports {
		if i == 0 {
			for j := 1; j < 4; j++ {
				_, m1, d1 := tools.GetNextDay(year, month, day, j-1)
				_, m, d := tools.GetNextDay(year, month, day, j)
				report.Data[j][0].Value = m1 + "月" + d1 + "日" + "20时" + "-" + m + "月" + d + "日" + "20时"
			}
		} else if i == 1 {
			for j := 2; j < 5; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "年" + m + "月" + d + "日"
				var liangmi models.Liangmi
				var liangmi8 models.Liangmi8
				db.Where("date = ?", timeNew).First(&liangmi)
				db.Where("date = ?", timeNew).First(&liangmi8)
				if liangmi.Id != 0 {
					report.Data[j][1].Value = liangmi.Data
					report.Data[j][2].Value = liangmi8.Data
				} else {
					report.Data[j][1].Value = ""
					report.Data[j][2].Value = ""
				}
			}
		} else {
			for j := 2; j < 5; j++ {
				y, m, d := tools.GetNextDay(year, month, day, j-1)
				report.Data[j][0].Value = m + "月" + d + "日"
				//timeNew := y + "年" + m + "月" + d + "日"
				//月和日补0
				if len(m) == 1 {
					m = "0" + m
				}
				if len(d) == 1 {
					d = "0" + d
				}
				timeNew := y + "-" + m + "-" + d
				//这部分操作与上传文件有关，时间那些
				var tide models.TwcTide
				db.Where("date = ? AND station = ?", timeNew, "浅滩").First(&tide)
				if tide.Id != 0 {
					report.Data[j][1].Value = tide.TimeHigh1
					report.Data[j][2].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideHigh1)/100, 2)
					report.Data[j][3].Value = tide.TimeHigh2
					report.Data[j][4].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideHigh2)/100, 2)
					report.Data[j][5].Value = tide.TimeLow1
					report.Data[j][6].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideLow1)/100, 2)
					report.Data[j][7].Value = tide.TimeLow2
					report.Data[j][8].Value = tools.Float64ToFixedStr(tools.StrToFloat64(tide.TideLow2)/100, 2)
				} else {
					for k := 1; k < 9; k++ {
						report.Data[j][k].Value = ""
					}
				}
			}
		}
	}
}

func handelHy(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for _, report := range forecast.Reports {
		for j := 1; j < 4; j++ {
			_, m1, d1 := tools.GetNextDay(year, month, day, j-1)
			_, m, d := tools.GetNextDay(year, month, day, j)
			report.Data[j][0].Value = m1 + "月" + d1 + "日" + "20时" + "-" + m + "月" + d + "日" + "20时"
		}
	}
}

func handelZb(forecast *models.Forecast, time string, db *gorm.DB) {
	timeArr := strings.Split(time, "-")
	year := timeArr[0]
	month := timeArr[1]
	day := timeArr[2]
	for _, report := range forecast.Reports {
		for j := 2; j < 9; j++ {
			y, m, d := tools.GetNextDay(year, month, day, j-1)
			report.Data[j][0].Value = m + "月" + d + "日"
			//timeNew := y + "年" + m + "月" + d + "日"
			//月和日补0
			if len(m) == 1 {
				m = "0" + m
			}
			if len(d) == 1 {
				d = "0" + d
			}
			timeNew := y + "年" + m + "月" + d + "日"
			var liangmi models.Liangmi
			var liangmi8 models.Liangmi8
			db.Where("date = ?", timeNew).First(&liangmi)
			db.Where("date = ?", timeNew).First(&liangmi8)
			if liangmi.Id != 0 {
				report.Data[j][1].Value = liangmi.Data
				report.Data[j][2].Value = liangmi8.Data
			} else {
				report.Data[j][1].Value = ""
				report.Data[j][2].Value = ""
			}
		}
	}
}

// SubmitForeData
func (ctl *WzCtl) SubmitForeData(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	time := c.Query("time")
	var req models.Forecast
	err = c.ShouldBindJSON(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var foredetail models.ForeDetail
	//	查询foreListId=id, time=time的数据
	ctl.db.Where("foreListId = ? AND time = ?", id, time).First(&foredetail)
	if foredetail.Id == 0 {
		tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		return
	}
	if foredetail.State != "2" {
		foredetail.State = "1"
	}
	ctl.db.Save(&foredetail)
	fileName := "./public/yubao/" + foredetail.Data + ".json"
	//	将req转为json
	jsonStr, err := json.Marshal(req)
	if err != nil {
		tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		return
	}
	//	将json以GBK编码写入文件
	encoder := simplifiedchinese.GBK.NewEncoder()
	gbkData, err := encoder.Bytes(jsonStr)
	if err != nil {
		tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		return
	}
	err = os.WriteFile(fileName, gbkData, 0666)
	if err != nil {
		tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		return
	}
	tools.SuccessResp(c, "提交成功", nil)
}

// SubAlarm
func (ctl *WzCtl) SubAlarm(c *gin.Context) {
	ctl.db = models.Db
	var alarmDetail models.AlarmDetail
	c.ShouldBind(&alarmDetail)
	if alarmDetail.Type == "天文潮" {
		alarmDetail.Bh = "天文潮" + tools.IntToStr(int(time.Now().Unix()))
	}
	//ctl.db.Create(&alarmDetail)
	ctl.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_bh_region"}},
		DoUpdates: clause.AssignmentColumns([]string{"state", "Type", "PubType", "Level", "Time", "FileName", "Data", "Data1", "SendTime"}),
	}).Create(&alarmDetail)
	//更新TwcSub
	//ctl.db.Model(&alarmDetail).Association("TwcSub").Replace(alarmDetail.TwcSub)
	if alarmDetail.State != "-1" {
		fileName := "./public/jb/" + alarmDetail.FileName
		//将文件复制并保存在 "./public/jb1/"目录下
		baseUrl := ctl.baseUrl

		err := services.GuiDang(fileName, baseUrl, &alarmDetail)
		if err != nil {
			tools.ErrorResp(c, 500, "文件归档失败")
			return
		}
	}
	//判断现在是哪一年
	//timeNow := alarmDetail.Time
	//year := strings.Split(timeNow, "-")[0]
	//
	//file, err := os.Open(fileName)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "")
	//	return
	//}
	//defer file.Close()
	//
	////获取文件名\\Chee\0局域网共享文件夹测试
	////dirName := baseUrl + "09_警报单" + "\\" + year + "\\" + alarmDetail.Subject + "\\" + name1 + alarmDetail.Subject + "\\" + regionMap[alarmDetail.Region]
	//dirName := ""
	//if alarmDetail.Type != "天文潮" {
	//	name1 := strings.Split(strings.Split(alarmDetail.Bh, " ")[1], "-")[0]
	//	dirName = baseUrl + "09_警报单" + "\\" + year + "\\" + alarmDetail.Subject + "\\" + name1 + alarmDetail.Subject + "\\" + regionMap[alarmDetail.Region]
	//} else {
	//	dirName = baseUrl + "09_警报单" + "\\" + year + "\\" + "天文大潮消息"
	//}
	////判断文件夹是否存在，不存在则创建
	//if _, err := os.Stat(dirName); err != nil {
	//	if os.IsNotExist(err) {
	//		err := os.MkdirAll(dirName, os.ModePerm)
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "文件夹创建失败")
	//			return
	//		}
	//	}
	//}
	////遍历文件夹，打印所有文件名
	//fileList := []string{}
	//filepath.Walk(dirName, func(path string, f os.FileInfo, err error) error {
	//	fileList = append(fileList, f.Name())
	//	return nil
	//})
	////判断fileList的所有文件名中是否有包含alarmDetail.Bh的文件名，如果有，则删除
	//for _, v := range fileList {
	//	if strings.Contains(v, alarmDetail.Bh) {
	//		err := os.Remove(dirName + "\\" + v)
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "文件删除失败")
	//			return
	//		}
	//	}
	//}
	//fileNameFinal := dirName + "\\" + alarmDetail.FileName
	//
	////创建文件
	//f, err := os.Create(fileNameFinal)
	//if err != nil {
	//	//tools.ErrorResp(c, 500, "文件创建失败")
	//	tools.ErrorResp(c, 500, "文件归档失败")
	//	return
	//}
	//defer f.Close()
	////将文件复制到f
	//_, err = io.Copy(f, file)
	//if err != nil {
	//	//tools.ErrorResp(c, 500, "文件复制失败")
	//	tools.ErrorResp(c, 500, "文件归档失败")
	//	return
	//}
	tools.SuccessResp(c, "提交成功", alarmDetail)
}

// DelAlarm
func (ctl *WzCtl) DelAlarm(c *gin.Context) {
	ctl.db = models.Db
	id := c.Query("id")
	var alarmDetail models.AlarmDetail
	ctl.db.Where("id = ?", id).First(&alarmDetail)
	if alarmDetail.Id == 0 {
		tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		return
	}
	ctl.db.Delete(&alarmDetail)
	tools.SuccessResp(c, "删除成功", nil)
}

// GetAlarm
func (ctl *WzCtl) GetAlarm(c *gin.Context) {
	ctl.db = models.Db
	region := c.Query("region")
	//t := c.Query("time")
	var alarmDetail []models.AlarmDetail
	//ctl.db.Preload("TwcSub").Where("DATE_FORMAT(time,'%Y-%m-%d') = ?", t).Find(&alarmDetail)
	//获取海浪，风暴潮，天文潮三个类型的最新一条数据，预加载TwcSub，每个类型只获取一个，一共三个
	//ctl.db.Preload("TwcSub").Where("type = ? OR type = ? OR type = ?", "海浪", "风暴潮", "天文潮").Order("time desc").Group("type").Find(&alarmDetail)

	tyes := [4]string{"海浪", "风暴潮", "天文潮", "海啸"}
	for _, v := range tyes {
		var alarmDetail1 models.AlarmDetail
		//ctl.db.Preload("TwcSub").Where("type = ?", v).Order("time desc").First(&alarmDetail1)
		//先根据时间排序，再根据id排序，取第一个,并且state=1
		ctl.db.Preload("TwcSub").Where("type = ? AND state = ? AND region = ?", v, "1", region).Order("time desc").Order("id desc").First(&alarmDetail1)
		//ctl.db.Preload("TwcSub").Where("type = ? AND state = ?", v, "1").Order("time desc").Order("id desc").First(&alarmDetail1)
		//ctl.db.Preload("TwcSub").Where("type = ?", v).Order("time desc").Order("id desc").First(&alarmDetail1)
		alarmDetail = append(alarmDetail, alarmDetail1)
	}
	tools.SuccessResp(c, "获取成功", alarmDetail)
}

//var regionMap = map[string]string{
//	"cn": "苍南近岸海域",
//	"py": "平阳近岸海域",
//	"ra": "瑞安近岸海域",
//	"sa": "三澳近岸海域",
//	"qt": "浅滩近岸海域",
//	"lw": "龙湾近岸海域",
//	"lg": "龙港近岸海域",
//}

// getAlarmLast
func (ctl *WzCtl) GetAlarmLast(c *gin.Context) {
	var err error
	ctl.db = models.Db
	t := c.Query("time")
	typeFinal := c.Query("type")
	pubType := c.Query("pubType")
	region := c.Query("region")
	var alarmDetail models.AlarmDetail

	var alarmDetailSave models.AlarmDetail
	err = ctl.db.Where("time <= ? AND type = ? AND pubType = ? AND region = ?", t, typeFinal, pubType, region).Order("time desc").Last(&alarmDetailSave).Error
	if err == nil {
		//tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		//tools.SuccessResp(c, "无上一次警报", nil)
		if alarmDetailSave.State == "-1" {
			alarmDetailSave.Message = "上一次保存的警报"
			tools.SuccessResp(c, "获取成功", alarmDetailSave)
			return
		}
	}
	if region != "wz" && typeFinal == "海浪" {
		//err = ctl.db.Where("time <= ? AND type = ? AND pubType = ? AND region = ?", t, typeFinal, pubType, "wz").Order("time desc").Last(&alarmDetail).Error
		if ctl.db.Where("time <= ? AND type = ? AND pubType = ? AND region = ?", t, typeFinal, pubType, "wz").Order("time desc").Last(&alarmDetail).RowsAffected == 0 {
			tools.SuccessResp(c, "无上一次警报", nil)
			return
		}
		//在没有新的wz警报的情况下查询县级警报，预填县级的上一次警报
		if alarmDetailSave.Bh == alarmDetail.Bh {
			alarmDetailSave.Message = "上一期警报"
			tools.SuccessResp(c, "获取成功", alarmDetailSave)
			return
		}
		alarmDetail.Message = "根据当前温州警报预填"
		if pubType == "警报" {
			services.HandleWave(&alarmDetail, region, ctl.db, c)
			return
		}
		if pubType == "消息" {
			services.HandleWaveInfo(&alarmDetail, region, ctl.db, c)
			return
		}
		if pubType == "警报解除通报" {
			services.HandleWaveJiechu(&alarmDetail, region, ctl.db, c)
			return
		}
		return
	} else if typeFinal == "风暴潮" {
		if ctl.db.Where("time <= ? AND type = ? AND pubType = ? AND region = ?", t, typeFinal, pubType, "wz").Order("time desc").Last(&alarmDetail).RowsAffected == 0 {
			tools.SuccessResp(c, "无上一次警报", nil)
			return
		}
		services.HandleFbc(&alarmDetail, region, ctl.db, c)
		return
	}
	//	获取时间在t之前，type为typeFinal，pubType为pubType的最新一条数据
	err = ctl.db.Where("time <= ? AND type = ? AND pubType = ? AND region = ?", t, typeFinal, pubType, region).Order("time desc").Last(&alarmDetail).Error
	if err != nil {
		//tools.ErrorResp(c, 500, "未知错误，请刷新重试")
		tools.SuccessResp(c, "无上一次警报", nil)
		return
	}
	alarmDetail.Message = "上一期警报"
	tools.SuccessResp(c, "获取成功", alarmDetail)
}

//	f, _ := excelize.OpenFile("./public/xlsx/RBR样例.xlsx")
//	cell, _ := f.GetCellValue("Data", "B8")
//	fmt.Println(cell)

// UploadRbr
//func (ctl *WzCtl) UploadRbr(c *gin.Context) {
//	var wg sync.WaitGroup
//	var err error
//	ctl.db = models.Db
//	numOffset := c.Query("numOffset")
//	file, err := c.FormFile("file")
//	if err != nil {
//		tools.ErrorResp(c, 500, "未知错误，请重新上传")
//		return
//	}
//	//	获取文件名
//	fileName := file.Filename
//	//	获取文件后缀
//	fileSuffix := path.Ext(fileName)
//	//	判断文件后缀
//	if fileSuffix != ".xlsx" {
//		tools.ErrorResp(c, 500, "文件格式错误，请重新上传")
//		return
//	}
//	//打开数据流
//	f, _ := file.Open()
//	xlsx, _ := excelize.OpenReader(f)
//	for _, v := range xlsx.GetSheetMap() {
//		if strings.Contains(v, "Data") {
//			rows, _ := xlsx.GetRows(v)
//			wg.Add(1)
//			go dealSheet(rows, v, &wg, ctl.db, numOffset)
//			wg.Add(1)
//			go dealSheetCut(rows, v, &wg, ctl.db, numOffset)
//		}
//	}
//	wg.Wait()
//	tools.SuccessResp(c, "上传成功", "555")
//}
//func dealSheet(rows [][]string, sheetName string, wg *sync.WaitGroup, db *gorm.DB, numOffset string) {
//	defer wg.Done()
//	var channel = make(chan models.Rbr, 1000000)
//	wg.Add(1)
//	go putData(channel, rows, sheetName, wg, numOffset)
//
//	for i := 0; i < 8; i++ {
//		wg.Add(1)
//		go saveData(channel, wg, db, numOffset)
//	}
//}
//
//func dealSheetCut(rows [][]string, sheetName string, wg *sync.WaitGroup, db *gorm.DB, numOffset string) {
//	defer wg.Done()
//	var channel = make(chan models.RbrCut, 1000000)
//	wg.Add(1)
//	go putDataCut(channel, rows, sheetName, wg, numOffset)
//
//	for i := 0; i < 8; i++ {
//		wg.Add(1)
//		go saveDataCut(channel, wg, db, numOffset)
//	}
//}
//
//func putData(channel chan models.Rbr, rows [][]string, sheetName string, wg *sync.WaitGroup, numOffset string) {
//	for index, row := range rows {
//		if index > 2 {
//			var test models.Rbr
//			timeFloat, _ := strconv.ParseFloat(row[0], 64)
//			timeResult := tools.ExcelDateToDate(timeFloat)
//			depthFloat, _ := strconv.ParseFloat(row[3], 64)
//			numOffsetFloat, _ := strconv.ParseFloat(numOffset, 64)
//			depthFloat += numOffsetFloat
//			depth := strconv.FormatFloat(depthFloat, 'f', -1, 64)
//			test.Time = timeResult
//			test.Depth = depth
//			channel <- test
//		}
//	}
//	close(channel)
//	wg.Done()
//}
//
//func putDataCut(channel chan models.RbrCut, rows [][]string, sheetName string, wg *sync.WaitGroup, numOffset string) {
//	for index, row := range rows {
//		if index > 4 && index < len(rows)-3 {
//			depthFloat, _ := strconv.ParseFloat(row[3], 64)
//			depthFloatLast, _ := strconv.ParseFloat(rows[index-1][3], 64)
//			depthFloatNext, _ := strconv.ParseFloat(rows[index+1][3], 64)
//			if (depthFloat > depthFloatLast && depthFloat > depthFloatNext) || (depthFloat < depthFloatLast && depthFloat < depthFloatNext) {
//				var test models.RbrCut
//				timeFloat, _ := strconv.ParseFloat(row[0], 64)
//				timeResult := tools.ExcelDateToDate(timeFloat)
//				//depthFloat, _ := strconv.ParseFloat(row[3], 64)
//				numOffsetFloat, _ := strconv.ParseFloat(numOffset, 64)
//				depthFloat += numOffsetFloat
//				depth := strconv.FormatFloat(depthFloat, 'f', -1, 64)
//				test.Time = timeResult
//				test.Depth = depth
//				channel <- test
//			}
//		}
//	}
//	close(channel)
//	wg.Done()
//}
//
//func saveData(channel chan models.Rbr, wg *sync.WaitGroup, db *gorm.DB, numOffset string) {
//	defer wg.Done()
//	var testList []models.Rbr
//	for test := range channel {
//		testList = append(testList, test)
//		if len(testList) == 2000 {
//			models.Db.Clauses(clause.OnConflict{
//				Columns:   []clause.Column{{Name: "time"}},
//				DoUpdates: clause.AssignmentColumns([]string{"depth"}),
//			}).Create(&testList)
//			testList = nil
//		}
//	}
//}
//
//func saveDataCut(channel chan models.RbrCut, wg *sync.WaitGroup, db *gorm.DB, numOffset string) {
//	defer wg.Done()
//	var testList []models.RbrCut
//	for test := range channel {
//		testList = append(testList, test)
//		if len(testList) == 2000 {
//			models.Db.Clauses(clause.OnConflict{
//				Columns:   []clause.Column{{Name: "time"}},
//				DoUpdates: clause.AssignmentColumns([]string{"depth"}),
//			}).Create(&testList)
//			testList = nil
//		}
//	}
//}

// GetTideList
func (ctl *WzCtl) GetTideList(c *gin.Context) {
	ctl.db = models.Db
	tideType := c.Query("type")
	station := c.Query("station")
	if tideType == "all" {
		var tideList []models.Rbr
		ctl.db.Where("station=?", station).Find(&tideList)
		tools.SuccessResp(c, "获取成功", tideList)
		return
	}
	var tideList []models.RbrCut
	//ctl.db.Where("station=?", station).Find(&tideList)
	//获取时间排序最新一条数据
	var tideList1 models.RbrCut
	ctl.db.Where("station=?", station).Order("time desc").First(&tideList1)
	//时间向前推15天
	time1, _ := time.Parse("2006-01-02 15:04:05", tideList1.Time)
	time2 := time1.AddDate(0, 0, -5)
	//获取时间在time2之后的数据
	ctl.db.Where("station=? AND time > ?", station, time2).Find(&tideList)
	tools.SuccessResp(c, "获取成功", tideList)
}

// GetLogList
func (ctl *WzCtl) GetLogList(c *gin.Context) {
	ctl.db = models.Db
	var logList []models.Log
	//ctl.db.Find(&logList)
	//tools.SuccessResp(c, "获取成功", logList)

	page := c.Query("page")
	limit := c.Query("limit")
	t := c.Query("time")
	//	获取范围内的数据
	limitInt, _ := strconv.Atoi(limit)
	pageInt, _ := strconv.Atoi(page)
	//倒序获取该天的数据
	ctl.db.Where("DATE_FORMAT(time,'%Y-%m-%d') = ?", t).Order("id desc").Limit(limitInt).Offset((pageInt - 1) * limitInt).Find(&logList)
	//获取总数
	var count int64
	ctl.db.Model(&models.Log{}).Where("DATE_FORMAT(time,'%Y-%m-%d') = ?", t).Count(&count)
	tools.SuccessResp(c, "获取成功", gin.H{
		"list":  logList,
		"count": count,
	})
}

// GetLogCount
func (ctl *WzCtl) GetLogCount(c *gin.Context) {
	ctl.db = models.Db
	var count int64
	ctl.db.Model(&models.Log{}).Count(&count)
	tools.SuccessResp(c, "获取成功", count)
}

// GetUserList
func (ctl *WzCtl) GetUserList(c *gin.Context) {
	ctl.db = models.Db
	var userList []models.User
	ctl.db.Preload("Role.Right").Find(&userList)
	tools.SuccessResp(c, "获取成功", userList)
}

func (ctl *WzCtl) GetTwcList(c *gin.Context) {
	ctl.db = models.Db
	dateStart := c.Query("dateStart")
	dateEnd := c.Query("dateEnd")
	station := c.Query("station")
	//转为字符串数组
	stationList := strings.Split(station, ",")
	var twcList []models.TwcTide

	//获取时间范围内，station在stationList中的数据
	ctl.db.Where("date >= ? AND date <= ? AND station IN (?)", dateStart, dateEnd, stationList).Find(&twcList)
	for i, v := range twcList {
		twcList[i].TideHigh1 = tools.Float64ToFixedStr(tools.StrToFloat64(v.TideHigh1), 0)
		twcList[i].TideHigh2 = tools.Float64ToFixedStr(tools.StrToFloat64(v.TideHigh2), 0)
		twcList[i].TideLow1 = tools.Float64ToFixedStr(tools.StrToFloat64(v.TideLow1), 0)
		twcList[i].TideLow2 = tools.Float64ToFixedStr(tools.StrToFloat64(v.TideLow2), 0)
		//fmt.Println(v.TideHigh1, twcList[i].TideHigh1)
	}
	//ctl.db.Where("date >= ? AND date <= ?", dateStart, dateEnd).Find(&twcList)
	tools.SuccessResp(c, "获取成功", twcList)
}

// UpdateUser
func (ctl *WzCtl) UpdateUser(c *gin.Context) {
	ctl.db = models.Db
	var user models.User
	c.ShouldBind(&user)
	ctl.db.Save(&user)
	tools.SuccessResp(c, "修改成功", nil)
}

// GetRoleList
func (ctl *WzCtl) GetRoleList(c *gin.Context) {
	ctl.db = models.Db
	var roleList []models.Role
	ctl.db.Preload("Right").Find(&roleList)
	tools.SuccessResp(c, "获取成功", roleList)
}

// GetRightList
func (ctl *WzCtl) GetRightList(c *gin.Context) {
	ctl.db = models.Db
	var rightList []models.Right
	ctl.db.Find(&rightList)
	tools.SuccessResp(c, "获取成功", rightList)
}

// SubSetting
func (ctl *WzCtl) SubSetting(c *gin.Context) {
	ctl.db = models.Db
	var setting models.Settting
	c.ShouldBind(&setting)
	//将id为1的数据更新
	ctl.db.Model(&models.Settting{}).Where("id = ?", 1).Updates(setting)
	tools.SuccessResp(c, "修改成功", nil)
}

// AddRight
func (ctl *WzCtl) AddRight(c *gin.Context) {
	ctl.db = models.Db
	var right models.Right
	c.ShouldBind(&right)
	ctl.db.Create(&right)
	tools.SuccessResp(c, "添加成功", nil)
}

// DelRight
func (ctl *WzCtl) DelRight(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	var right models.Right
	err = ctl.db.Where("id = ?", id).Delete(&right).Error
	if err != nil {
		tools.ErrorResp(c, 500, "删除失败")
	} else {
		tools.SuccessResp(c, "删除成功", nil)
	}
	//ctl.db.Where("id = ?", id).Delete(&right)
	//tools.SuccessResp(c, "删除成功", nil)
	//if right.ID == 0 {
	//	tools.ErrorResp(c, 500, "删除失败")
	//} else {
	//	tools.SuccessResp(c, "删除成功", nil)
	//}
}

// DelRole
func (ctl *WzCtl) DelRole(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	var role models.Role
	err = ctl.db.Where("id = ?", id).Delete(&role).Error
	if err != nil {
		tools.ErrorResp(c, 500, "删除失败")
	} else {
		tools.SuccessResp(c, "删除成功", nil)
	}
}

// AddUser
func (ctl *WzCtl) AddUser(c *gin.Context) {
	ctl.db = models.Db
	var user models.User
	c.ShouldBind(&user)
	//user.CreatedAt = time.Now().Format("2006-01-02 15:04:05")
	//user.UpdatedAt = time.Now().Format("2006-01-02 15:04:05")

	ctl.db.Create(&user)
}

// GetFbList
func (ctl *WzCtl) GetFbList(c *gin.Context) {
	ctl.db = models.Db
	station := c.Query("station")
	var fbList []models.Fb
	//ctl.db.Where("DATE_FORMAT(time,'%Y-%m-%d') = ?", t).Find(&fbList)

	//获取最新一条数据的时间
	var fb models.Fb
	if ctl.db.Where("station=?", station).Order("time desc").First(&fb).RowsAffected == 0 {
		tools.SuccessResp(c, "获取成功", nil)
		return
	}
	timeDay := strings.Split(fb.Time, " ")[0]
	//时间往前推一个周
	timeDayArr := strings.Split(timeDay, "-")
	year := timeDayArr[0]
	month := timeDayArr[1]
	day := timeDayArr[2]
	//获取最新一条数据的时间的前一周的时间
	y, m, d := tools.GetNextDay(year, month, day, -7)
	//补零
	if len(m) == 1 {
		m = "0" + m
	}
	if len(d) == 1 {
		d = "0" + d
	}
	timeNew := y + "-" + m + "-" + d + " 00:00"
	//获取时间在timeNew之后的数据
	//ctl.db.Where("time >= ?", timeNew).Find(&fbList)
	ctl.db.Where("station=? AND time >= ?", station, timeNew).Find(&fbList)
	tools.SuccessResp(c, "获取成功", fbList)
}

// deleteAlarm
func (ctl *WzCtl) DeleteAlarm(c *gin.Context) {
	ctl.db = models.Db
	id := c.Query("id")
	var alarm models.AlarmDetail
	ctl.db.Where("alarmDetailId = ?", id).Delete(&models.TwcSub{})
	ctl.db.Where("id = ?", id).Delete(&alarm)
	tools.SuccessResp(c, "删除成功", nil)
}

// UpdateFore
func (ctl *WzCtl) UpdateFore(c *gin.Context) {
	var err error
	ctl.db = models.Db
	id := c.Query("id")
	t := c.Query("time")
	state := c.Query("state")
	fileName := c.Query("fileName")
	var foreDetail models.ForeDetail
	ctl.db.Where("foreListId = ? AND time = ?", id, t).Find(&foreDetail)
	//foreDetail.State = state
	if state != "" {
		foreDetail.State = state
	}
	if fileName != "" {
		foreDetail.FileName = fileName
	}
	err = ctl.db.Save(&foreDetail).Error
	if err != nil {
		tools.ErrorResp(c, 500, "修改失败")
		return
	}
	//baseUrl := ctl.baseUrl
	//timeNow := foreDetail.Time
	//timeArr := strings.Split(timeNow, "-")
	//timeStr := timeArr[0] + timeArr[1] + timeArr[2]
	//year := timeArr[0]
	//dirName := baseUrl + "08_预报单" + "\\" + year + "\\" + timeStr
	//
	//file, err := os.Open("./public/ybd/" + foreDetail.FileName)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "文件不存在")
	//	return
	//}
	//defer file.Close()
	//
	//if _, err := os.Stat(dirName); err != nil {
	//	if os.IsNotExist(err) {
	//		err := os.MkdirAll(dirName, os.ModePerm)
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "文件夹创建失败")
	//			return
	//		}
	//	}
	//}
	//fileNameFinal := dirName + "\\" + foreDetail.FileName
	//
	////创建文件
	//f, err := os.Create(fileNameFinal)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "文件创建失败")
	//	return
	//}
	//defer f.Close()
	////将文件复制到f
	//_, err = io.Copy(f, file)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "文件复制失败")
	//	return
	//}
	tools.SuccessResp(c, "修改成功", nil)
}

func (ctl *WzCtl) SendForeFile(c *gin.Context) {
	ctl.db = models.Db
	var foreDetail models.ForeDetailJson
	c.ShouldBind(&foreDetail)
	if foreDetail.FileName == "" {
		tools.ErrorResp(c, 500, "文件不存在")
		return
	}
	baseUrl := ctl.baseUrl
	timeNow := foreDetail.Time
	timeArr := strings.Split(timeNow, "-")
	timeStr := timeArr[0] + timeArr[1] + timeArr[2]
	year := timeArr[0]
	dirName := baseUrl + "预报单" + "\\" + year + "\\" + timeStr
	//dirName := "C:\\Users\\chun\\GolandProjects\\sa-go\\public\\测试归档"
	types := []string{".docx", ".pdf"}

	var foreList models.ForeList
	ctl.db.Where("id = ?", foreDetail.ForeListId).Find(&foreList)
	if foreList.Code == "ydyl" || foreList.Code == "fb" {
		types = []string{".xlsx"}
	}
	//fileNames := []string{foreDetail.
	//}
	fileNames := handleGetFileNames(foreList.Code, foreDetail.FileName)
	for _, suffix := range types {
		for _, fileName := range fileNames {
			file, err := os.Open("./public/ybd/" + fileName + suffix)
			if err != nil {
				tools.ErrorResp(c, 500, "文件不存在")
				return
			}
			//defer file.Close()

			if _, err := os.Stat(dirName); err != nil {
				if os.IsNotExist(err) {
					err := os.MkdirAll(dirName, os.ModePerm)
					if err != nil {
						tools.ErrorResp(c, 500, "文件夹创建失败")
						return
					}
				}
			}
			fileNameFinal := dirName + "\\" + fileName + suffix
			//创建文件
			f, err := os.Create(fileNameFinal)
			if err != nil {
				tools.ErrorResp(c, 500, "文件创建失败")
				return
			}
			//defer f.Close()
			//将文件复制到f
			_, err = io.Copy(f, file)
			file.Close()
			f.Close()
			if err != nil {
				tools.ErrorResp(c, 500, "文件复制失败")
				return
			}
		}
	}

	tools.SuccessResp(c, "发送成功", nil)
}

func (ctl *WzCtl) SendForeFileRaqx(c *gin.Context) {
	ctl.db = models.Db
	var foreDetail models.ForeDetailJson
	c.ShouldBind(&foreDetail)
	if foreDetail.FileName == "" {
		tools.ErrorResp(c, 500, "文件不存在")
		return
	}
	baseUrl := ctl.baseUrl
	timeNow := foreDetail.Time
	timeArr := strings.Split(timeNow, "-")
	timeStr := timeArr[0] + timeArr[1] + timeArr[2]
	year := timeArr[0]
	dirName := baseUrl + "预报单" + "\\" + year + "\\" + timeStr + "\\" + "瑞安气象"
	types := []string{".docx", ".pdf"}

	var foreList models.ForeList
	ctl.db.Where("id = ?", foreDetail.ForeListId).Find(&foreList)
	if foreList.Code == "ydyl" || foreList.Code == "fb" {
		types = []string{".xlsx"}
	}
	//fileNames := []string{foreDetail.
	//}
	fileNames := handleGetFileNames(foreList.Code, foreDetail.FileName)
	fmt.Println(fileNames)
	tools.SuccessResp(c, "发送成功", nil)
	//return
	for _, suffix := range types {
		for _, fileName := range fileNames {
			file, err := os.Open("./public/ybd/" + fileName + "_qx" + suffix)
			if err != nil {
				tools.ErrorResp(c, 500, "文件不存在")
				return
			}
			defer file.Close()

			if _, err := os.Stat(dirName); err != nil {
				if os.IsNotExist(err) {
					err := os.MkdirAll(dirName, os.ModePerm)
					if err != nil {
						tools.ErrorResp(c, 500, "文件夹创建失败")
						return
					}
				}
			}
			fileNameFinal := dirName + "\\" + fileName + suffix

			//创建文件
			f, err := os.Create(fileNameFinal)
			if err != nil {
				tools.ErrorResp(c, 500, "文件创建失败")
				return
			}
			defer f.Close()
			//将文件复制到f
			_, err = io.Copy(f, file)
			if err != nil {
				tools.ErrorResp(c, 500, "文件复制失败")
				return
			}
		}
	}

	tools.SuccessResp(c, "发送成功", nil)
}

// handleGetFileNames
func handleGetFileNames(code, fileName string) []string {
	var fileNames []string
	if code == "yy" {
		baseName := strings.Split(fileName, "-")[0]
		tArr := strings.Split(strings.Split(fileName, "-")[1], "_")
		fileNames = []string{baseName + "-" + "24_" + tArr[1] + "_24", baseName + "-" + "48_" + tArr[1] + "_48"}
	} else if code == "rahx" {
		baseName := strings.Split(fileName, "——")[0]
		fileNames = []string{baseName + "——" + "24小时", baseName + "——" + "48小时", baseName + "——" + "72小时"}
	} else if code == "rayg" {
		baseName := strings.Split(fileName, "——")[0]
		fileNames = []string{baseName + "——" + "24小时", baseName + "——" + "48小时", baseName + "——" + "72小时"}
	} else {
		fileNames = []string{fileName}
	}

	return fileNames
}

func (ctl *WzCtl) GetForeTable(c *gin.Context) {
	ctl.db = models.Db
	id := c.Query("id")
	time := c.Query("time")
	var foreDetail models.ForeDetail
	ctl.db.Where("foreListId = ? AND time = ?", id, time).First(&foreDetail)
	tools.SuccessResp(c, "获取成功", foreDetail)
}

func (ctl *WzCtl) SendFore(c *gin.Context) {
	var err error
	ctl.db = models.Db
	var sendLog models.SendLog
	c.ShouldBind(&sendLog)
	sendLog.SendTime = time.Now().Format("2006-01-02 15:04:05")
	sendLog.State = "1"
	err = ctl.db.Create(&sendLog).Error
	if err != nil {
		tools.ErrorResp(c, 500, "日志保存失败")
		return
	}
	alarmId := sendLog.AlarmId
	var alarmDetail models.AlarmDetail
	ctl.db.Where("id = ?", alarmId).Find(&alarmDetail)
	if alarmDetail.Id == 0 {
		tools.SuccessResp(c, "日志保存成功", nil)
		return
	}
	alarmDetail.State = "1"
	alarmDetail.SendTime = time.Now().Format("2006-01-02 15:04:05")
	err = ctl.db.Save(&alarmDetail).Error
	if err != nil {
		//tools.ErrorResp(c, 500, "修改失败")
		tools.SuccessResp(c, "日志保存成功", nil)
		return
	}
	tools.SuccessResp(c, "日志保存成功", nil)
}

// getAlarmByConfig
func (ctl *WzCtl) GetAlarmByConfig(c *gin.Context) {
	ctl.db = models.Db
	//var alarmList []models.AlarmDetail
	var alarm models.AlarmDetail
	var err error
	t := c.Query("time")
	alarmType := c.Query("type")
	pubType := c.Query("pubType")
	level := c.Query("level")
	//err = ctl.db.Where("time = ? AND type = ? AND pubType = ? AND level = ?", t, alarmType, pubType, level).Find(&alarmList).Error
	//获取最新的一条数据
	err = ctl.db.Where("time = ? AND type = ? AND pubType = ? AND level = ?", t, alarmType, pubType, level).Order("id desc").First(&alarm).Error
	if err != nil {
		tools.ErrorResp(c, 500, "获取失败")
		return
	}
	tools.SuccessResp(c, "获取成功", alarm)
}

// GetTf
func (ctl *WzCtl) GetTf(c *gin.Context) {
	ctl.db = models.Db
	var tfList []models.Tf
	ctl.db.Find(&tfList)
	tools.SuccessResp(c, "获取成功", tfList)
}

// GetAlarmLastByBh
func (ctl *WzCtl) GetAlarmLastByBh(c *gin.Context) {
	var err error
	ctl.db = models.Db
	t := c.Query("time")
	typeFinal := c.Query("type")
	//pubType := c.Query("pubType")
	bh := c.Query("bh")
	region := c.Query("region")
	var alarmDetail models.AlarmDetail
	//	获取时间在t之前，type为typeFinal，pubType为pubType,state=1的最新一条数据,bh包含bh的
	err = ctl.db.Where("time <= ? AND type = ? AND state = ? AND region = ? AND bh like ?", t, typeFinal, "1", region, "%"+bh+"%").Order("time desc").Last(&alarmDetail).Error
	//err = ctl.db.Where("time <= ? AND type = ? AND bh like ?", t, typeFinal, "%"+bh+"%").Order("time desc").Last(&alarmDetail).Error
	if err != nil {
		tools.SuccessResp(c, "无上一次警报", nil)
		return
	}
	if alarmDetail.PubType == "警报解除通报" {
		tools.SuccessResp(c, "无上一次警报", nil)
		return
	}
	tools.SuccessResp(c, "获取成功", alarmDetail)
}

// Register
//func (ctl *WzCtl) Register(c *gin.Context) {
//	ctl.db = models.Db
//	var user models.User
//	c.ShouldBind(&user)
//	//user.CreatedAt = time.Now().Format("2006-01-02 15:04:05")
//	//user.UpdatedAt = time.Now().Format("2006-01-02 15:04:05")
//	//	判断用户名是否存在
//	var user1 models.User
//	ctl.db.Where("username = ?", user.Username).First(&user1)
//	if user1.Id != 0 {
//		tools.ErrorResp(c, 500, "用户名已存在")
//		return
//	}
//	ctl.db.Create(&user)
//	tools.SuccessResp(c, "注册成功", nil)
//}

// GetTideByHour
func (ctl *WzCtl) GetTideByHour(c *gin.Context) {
	ctl.db = models.Db
	date := c.Query("date")
	station := c.Query("station")
	var tideHourList []models.TideHour
	//ctl.db.Where("date = ?", date).Find(&tideHourList)
	ctl.db.Where("date = ? AND station = ?", date, station).Find(&tideHourList)
	tools.SuccessResp(c, "获取成功", tideHourList)
}

// 获取最近一次周报
func (ctl *WzCtl) GetLastWeek(c *gin.Context) {
	ctl.db = models.Db
	var week models.ForeDetailJson
	//ctl.db.Where("foreListId = ?", "3").Order("time desc").First(&week)
	//state！=0
	ctl.db.Where("foreListId = ? AND state != ?", "3", "0").Order("time desc").First(&week)
	//jsonName := "./public/yubao/" + week.Data + ".json"
	//if _, err := os.Stat(jsonName); err != nil {
	//	tools.ErrorResp(c, 500, "暂无周报")
	//	return
	//}
	//file, err := os.ReadFile(jsonName)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "暂无周报")
	//	return
	//}
	//decoder := simplifiedchinese.GBK.NewDecoder()
	//file, _ = decoder.Bytes(file)
	//
	//var forecast = models.Forecast{}
	//json.Unmarshal(file, &forecast)
	tools.SuccessResp(c, "获取成功", week.Data)
}

// getAlarmByDay
func (ctl *WzCtl) GetAlarmByDay(c *gin.Context) {
	ctl.db = models.Db
	var alarmList []models.AlarmDetail
	t := c.Query("time")
	//ctl.db.Where("DATE_FORMAT(time,'%Y-%m-%d') = ? AND state = ?", t, "1").Find(&alarmList)

	ctl.db.Where("DATE_FORMAT(time,'%Y-%m-%d') = ? AND state != ?", t, "-1").Find(&alarmList)
	//alarmList中的updated_at字段是时间戳，需要转换为时间格式
	for i, v := range alarmList {
		alarmList[i].FormatTime = tools.TimeStampToDate(v.UpdatedAt)
	}
	tools.SuccessResp(c, "获取成功", alarmList)
}

// getAlarmType
func (ctl *WzCtl) GetAlarmType(c *gin.Context) {
	ctl.db = models.Db
	code := c.Query("code")
	var alarmList models.AlarmType
	ctl.db.Where("code = ?", code).First(&alarmList)
	tools.SuccessResp(c, "获取成功", alarmList)
}

// updateAlarmType
func (ctl *WzCtl) UpdateAlarmType(c *gin.Context) {
	ctl.db = models.Db
	var alarmList models.AlarmType
	c.ShouldBind(&alarmList)
	ctl.db.Save(&alarmList)
	tools.SuccessResp(c, "修改成功", nil)
}

var regionMap = map[string]string{
	"wz": "温州",
	"cn": "苍南",
	"py": "平阳",
	"ra": "瑞安",
	"sa": "三澳",
	"qt": "浅滩",
	"lw": "龙湾",
	"lg": "龙港",
}

// updateAlarmDetail
func (ctl *WzCtl) UpdateAlarmDetail(c *gin.Context) {
	ctl.db = models.Db
	var alarmList models.AlarmDetail
	c.ShouldBind(&alarmList)
	ctl.db.Save(&alarmList)
	//fileName := "./public/jb/" + alarmList.FileName
	////将文件复制并保存在 "./public/jb1/"目录下
	//baseUrl := ctl.baseUrl
	////判断现在是哪一年
	//timeNow := alarmList.Time
	//year := strings.Split(timeNow, "-")[0]
	//name1 := strings.Split(strings.Split(alarmList.Bh, " ")[1], "-")[0]
	//file, err := os.Open(fileName)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "文件不存在")
	//	return
	//}
	//defer file.Close()
	////获取文件名\\Chee\0局域网共享文件夹测试
	//dirName := baseUrl + "09_警报单" + "\\" + year + "\\" + alarmList.Subject + "\\" + name1 + alarmList.Subject + "\\" + regionMap[alarmList.Region]
	////判断文件夹是否存在，不存在则创建
	//if _, err := os.Stat(dirName); err != nil {
	//	if os.IsNotExist(err) {
	//		err := os.MkdirAll(dirName, os.ModePerm)
	//		if err != nil {
	//			tools.ErrorResp(c, 500, "文件夹创建失败")
	//			return
	//		}
	//	}
	//}
	//fileNameFinal := dirName + "\\" + alarmList.FileName
	//
	////创建文件
	//f, err := os.Create(fileNameFinal)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "文件创建失败")
	//	return
	//}
	//defer f.Close()
	////将文件复制到f
	//_, err = io.Copy(f, file)
	//if err != nil {
	//	tools.ErrorResp(c, 500, "文件复制失败")
	//	return
	//}

	tools.SuccessResp(c, "修改成功", nil)
}

// delAlarmDetail
func (ctl *WzCtl) DelAlarmDetail(c *gin.Context) {
	ctl.db = models.Db
	id := c.Query("id")
	var alarmList models.AlarmDetail
	//ctl.db.Where("id = ?", id).Delete(&alarmList)
	//并且删除所有的子表数据
	ctl.db.Where("alarmDetailId = ?", id).Delete(&models.TwcSub{})
	ctl.db.Where("id = ?", id).Delete(&alarmList)
	tools.SuccessResp(c, "删除成功", nil)
}

type TwcReq struct {
	Data []struct {
		Station   string `json:"station"`
		Date      string `json:"date"`
		TideHigh1 string `json:"tideHigh1"`
		TideHigh2 string `json:"tideHigh2"`
	} `json:"data"`
}

// updateTwcTide
func (ctl *WzCtl) UpdateTwcTide(c *gin.Context) {
	ctl.db = models.Db
	var twcTideList []models.TwcTide
	c.ShouldBind(&twcTideList)
	for _, v := range twcTideList {
		if v.TideHigh1 != "" {
			ctl.db.Model(&models.TwcTide{}).Where("station = ? AND date = ?", v.Station, v.Date).Update("tideHigh1", v.TideHigh1)
		} else if v.TideHigh2 != "" {
			ctl.db.Model(&models.TwcTide{}).Where("station = ? AND date = ?", v.Station, v.Date).Update("tideHigh2", v.TideHigh2)
		}
	}
	tools.SuccessResp(c, "修改成功", nil)
}

// 根据日期获取该日期的condition表的数据
func (ctl *WzCtl) GetConditionByDate(c *gin.Context) {
	ctl.db = models.Db
	date := c.Query("date")
	var conditionList []models.Condition
	ctl.db.Where("date = ?", date).Find(&conditionList)
	tools.SuccessResp(c, "获取成功", conditionList)
}

//bytes="" 字符串	&json={data：[
//					{
//					FaxNum:[{Num:287770}],
//					FilePath:"文件名"相对路径
//					FileData:""
//					}
//					]}

type FaxNum struct {
	Num string `json:"Num"`
}

type FaxData struct {
	FaxNum   []FaxNum `json:"FaxNum"`
	FilePath string   `json:"FilePath"`
	FileData string   `json:"FileData"`
}

// sendFax
type sendFaxReq struct {
	Num      []string `json:"num"`
	FilePath []string `json:"filePath"`
	Url      string   `json:"url"`
}

func (ctl *WzCtl) SendFax(c *gin.Context) {
	var senReq sendFaxReq
	_ = c.ShouldBind(&senReq)
	//fmt.Println(senReq)
	//filePath := "public/jb/231218-04 苍南海浪蓝色警报.doc"
	filePath := senReq.FilePath
	url := senReq.Url

	var faxNum []FaxNum
	for _, v := range senReq.Num {
		faxNum = append(faxNum, FaxNum{Num: v})

	}

	var data []FaxData
	//var fileData string
	for _, filePathItem := range filePath {
		//读取文件并转为为base64字符串
		file, err := os.Open("./" + filePathItem)
		if err != nil {
			// 处理错误
			fmt.Println(111)
		}
		//defer file.Close()
		//获取文件大小
		stat, err := file.Stat()
		if err != nil {
			// 处理错误
			fmt.Println(err)
		}

		//读取文件
		fileBytes := make([]byte, stat.Size())
		_, err = file.Read(fileBytes)
		if err != nil {
			// 处理错误
			fmt.Println(err)
		}
		_ = file.Close()
		//转为base64字符串
		fileData := base64.StdEncoding.EncodeToString(fileBytes)
		data = append(data, FaxData{
			FaxNum:   faxNum,
			FilePath: filePathItem,
			FileData: fileData,
		})
	}

	//data转为字符串
	dataBytes, _ := json.Marshal(data)
	dataStr := string(dataBytes)
	dataStr = "&json={" + `"data":` + dataStr + "}"
	//http://192.168.10.78:81/FaxPushInterFace/FaxIHandler.ashx
	//转为字符串http://localhost:5475/FaxPushInterFace/FaxIHandler.ashx
	req, err := http.NewRequest("POST", url, strings.NewReader(dataStr))
	if err != nil {
		fmt.Println(err)
		// 处理错误
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	contentLength := strconv.Itoa(len(dataStr))
	req.Header.Set("Content-Length", contentLength)

	client := http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// 处理错误
		fmt.Println(err)
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// 处理错误
		fmt.Println(err)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"body": string(body),
	})
}

var wxConfigMap = map[string]map[string]string{
	"海浪消息": {
		"touser":      "",
		"template_id": "2clBBROKzk9s4kH8I02jzH-ErKSixVGt8YTR8KmVW5I",
		"data":        "您好，温州市海洋预报台发布海浪消息！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
	"海浪警报": {
		//"touser": "oQu-76FdLWMQjepzuoGA6NeKdqRI",
		//	8ZuRxpKPQcqzLkzBuVUeoRmr4VJx68lTm8IpergXwxs
		//"template_id": "jJGo7oNEgQnnqAWMIDHJiDR2AYa74rPaXahq5svhV_Q",
		"touser":      "",
		"template_id": "2clBBROKzk9s4kH8I02jzH-ErKSixVGt8YTR8KmVW5I",
		"data":        "您好，温州市海洋预报台发布海浪警报！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
	"海浪警报解除通报": {
		"touser":      "",
		"template_id": "v3wE_XHA3aX2FhAHcOWmtXH4EtllhBVwQiovp7naOK4",
		"data":        "您好，温州市海洋预报台发布海浪警报解除通报！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
	"风暴潮消息": {
		"touser":      "",
		"template_id": "HJa-Ot2AnEXUFTCDIu2S_S5TIn_9A0L-Achhr5ZH_-I",
		"data":        "您好，温州市海洋预报台发布风暴潮消息！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
	"风暴潮警报": {
		"touser":      "",
		"template_id": "HJa-Ot2AnEXUFTCDIu2S_S5TIn_9A0L-Achhr5ZH_-I",
		"data":        "您好，温州市海洋预报台发布风暴潮警报！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
	"风暴潮警报解除通报": {
		"touser":      "",
		"template_id": "4U1ZSsCufhcPctjpA-yqCHhJ_7tO051IOJix6i1W2bg",
		"data":        "您好，温州市海洋预报台发布风暴潮警报解除通报！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
	"天文潮消息": {
		"touser":      "",
		"template_id": "oWu4QjxDbut4n1RSmONhEU69DCkAwX-P9rZIFf15YUk",
		"data":        "您好，温州市海洋预报台发布天文潮高潮位消息！",
		"url":         "http://www.wzhy.com.cn:8000/czx/#/warn",
	},
}

type wxToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type wxUser struct {
	Total int `json:"total"`
	Count int `json:"count"`
	Data  struct {
		Openid []string `json:"openid"`
	} `json:"data"`
	NextOpenid string `json:"next_openid"`
}

func (ctl *WzCtl) SendWxModel(c *gin.Context) {
	ctl.db = models.Db
	//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx01bac32f21e2aef2&secret=763611096f584d796b7a6f390c16294a
	//发送post请求
	respT, err1 := http.Post("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx01bac32f21e2aef2&secret=763611096f584d796b7a6f390c16294a", "application/json; encoding=utf-8", nil)
	if err1 != nil {
		// 处理错误
	}
	defer respT.Body.Close()
	// 读取响应内容
	body1, err2 := ioutil.ReadAll(respT.Body)
	if err2 != nil {
		// 处理错误
	}
	var wt wxToken
	_ = json.Unmarshal(body1, &wt)

	sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + wt.AccessToken
	var alarmDetail models.AlarmDetail
	_ = c.ShouldBind(&alarmDetail)
	key := alarmDetail.Type + alarmDetail.PubType
	color := services.GetWlevel(alarmDetail.PubType, alarmDetail.Level)
	if strings.Contains(alarmDetail.PubType, "色") {
		color = ""
	}
	wxConfig := wxConfigMap[key]
	//	格式化时间alarmDetail.Time，格式为yyyy年MM月dd日HH时
	timeArr := strings.Split(alarmDetail.Time, " ")
	timeArr1 := strings.Split(timeArr[0], "-")
	timeArr2 := strings.Split(timeArr[1], ":")
	timeStr := timeArr1[0] + "年" + timeArr1[1] + "月" + timeArr1[2] + "日" + timeArr2[0] + "时"
	keywordValue := alarmDetail.Bh
	if alarmDetail.Type == "天文潮" {
		keywordValue = "24小时"
	}
	strArr := [][2]string{
		{"first", wxConfig["data"]},
		{"keyword1", timeStr},
		{"keyword2", keywordValue},
	}
	if color != "" {
		strArr = append(strArr, [2]string{"keyword3", color})
	}
	remark := ""
	strArr = append(strArr, [2]string{"remark", remark})
	data := services.SetWxModel(strArr)

	//获取用户id
	urlUser := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + wt.AccessToken + "&next_openid="
	respU, errU := http.Post(urlUser, "application/json; encoding=utf-8", nil)
	if errU != nil {
		// 处理错误
		fmt.Println(errU)
	}
	defer respU.Body.Close()
	// 读取响应内容
	bodyU, errU := ioutil.ReadAll(respU.Body)
	if errU != nil {
		// 处理错误
	}
	var wu wxUser
	_ = json.Unmarshal(bodyU, &wu)

	for _, v := range wu.Data.Openid {
		strs := map[string]any{
			"touser":      v,
			"template_id": wxConfig["template_id"],
			"data":        data,
			"url":         wxConfig["url"],
		}
		//	strs转为字符串
		strsBytes, _ := json.Marshal(strs)
		strsStr := string(strsBytes)
		bytesLength := strconv.Itoa(len(strsStr))

		//	发送请求
		req, err := http.NewRequest("POST", sendUrl, strings.NewReader(strsStr))
		if err != nil {
			// 处理错误
		}
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Content-Length", bytesLength)
		client := http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			// 处理错误
		}
		defer resp.Body.Close()
		// 读取响应内容

	}

	c.JSON(200, gin.H{
		"code": 200,
		"body": "发送成功",
	})

	//strs := map[string]any{
	//	"touser":      wxConfig["touser"],
	//	"template_id": wxConfig["template_id"],
	//	"data":        data,
	//	"url":         wxConfig["url"],
	//}
	////	strs转为字符串
	//strsBytes, _ := json.Marshal(strs)
	//strsStr := string(strsBytes)
	//bytesLength := strconv.Itoa(len(strsStr))
	//
	//
	////	发送请求
	//req, err := http.NewRequest("POST", sendUrl, strings.NewReader(strsStr))
	//if err != nil {
	//	// 处理错误
	//}
	//req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	//req.Header.Set("Content-Length", bytesLength)
	//client := http.Client{}
	//resp, err := client.Do(req)
	//if err != nil {
	//	// 处理错误
	//}
	//defer resp.Body.Close()
	//// 读取响应内容
	//body, err := ioutil.ReadAll(resp.Body)
	//if err != nil {
	//	// 处理错误
	//}
	//c.JSON(200, gin.H{
	//	"code": 200,
	//	"body": string(body),
	//})
}
